package net.xdclass.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.model.LoginUser;

import java.util.Date;

/**
 * @Classname JwtUtil
 * @Description TODO
 * @Date 2022/4/15 16:45
 * @Created by sunhao
 */
@Slf4j
public class JwtUtil {

  /**
   * token 过期时间 正常是 7 天 方便测试改成70
   */
  public static final long EXPIRE = 1000 * 60 * 60 * 24 * 7 * 10;

  /**
   * 加密的密钥
   */
  private static final String SECRET = "xdclass.net666";

  /**
   * 令牌的前缀
   */
  private static final String TOKEN_PREFIX = "xdclass1024shop";


  /**
   * subject
   */
  private static final String SUBJECT = "xdclass";


  /**
   * 根据用户信息，生成令牌
   *
   * @param user
   * @return
   */
  public static String geneJsonWebToken(LoginUser user) {
    Long userId = user.getId();
    String token = Jwts.builder().setSubject(SUBJECT)
        .claim("head_img", user.getHeadImg())
        .claim("id", userId)
        .claim("name", user.getName())
        .claim("mail", user.getMail())
        .setIssuedAt(new Date())
        .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
        .signWith(SignatureAlgorithm.HS256, SECRET).compact();
    token = TOKEN_PREFIX + token;
    return token;
  }


  /**
   * 校验token
   * @param token
   * @return
   */
  public static Claims checkJwt(String token){
    final Claims claims;
    try {
      claims = Jwts.parser().setSigningKey(SECRET)
          .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();
      return claims;
    } catch (Exception e) {
      log.info("jwt token 解析失败!{}"+e);
    }
    return null;
  }
}
